/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tarena.lbs.attach.controller;

import com.tarena.lbs.attach.pojo.vo.FileVO;
import com.tarena.lbs.base.protocol.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

//@Api(value = "attach", tags = "附件中心管理")
//@CrossOrigin
@Slf4j
@Validated
@RestController
@RequestMapping("attach")
@Tag(name = "附件服务", description = "附件中心管理")
public class AttachController {

    @Value("${spring.web.resources.static-locations}")
    private String dirPath;

    @Value("${image_path}")
    private String imagePath;

    @Value("${url}")
    private String baseUrl;


    public Result<FileVO> uploadAttachInfo(@RequestPart("file") MultipartFile file) throws Exception {
        try {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
//            String dirPath = "d:/files";
            String dirPath = imagePath;
            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            String datePath = sdf.format(new Date());
            File dirFile = new File(dirPath + datePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            String filePath = dirPath + datePath + fileName;
            file.transferTo(new File(filePath));
            FileVO fileVO = new FileVO();
            fileVO.setFileUuid(fileName);
            fileVO.setUrl(baseUrl + datePath + fileName);
            return new Result<>(fileVO);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return Result.fail("FILE_FAIL", "文件上传失败");
        }
    }

    @PostMapping("upload")
    @Operation(summary = "上传附件")
    public Result<FileVO> uploadAttachInfo1(
            @RequestPart("file") MultipartFile file) throws Exception {
        try {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
//            String dirPath = "d:/files";
            String dirPath = imagePath;
            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            String datePath = sdf.format(new Date());
            datePath = datePath.substring(1);
            File dirFile = new File(dirPath + datePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            String filePath = dirPath + datePath + fileName;
            file.transferTo(new File(filePath));
            FileVO fileVO = new FileVO();
            fileVO.setFileUuid(fileName);
            fileVO.setUrl(baseUrl + datePath + fileName);
            return new Result<>(fileVO);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return Result.fail("FILE_FAIL", "文件上传失败");
        }

    }

    @Operation(summary = "删除文件")
    @PostMapping("delete")
    public Result<Void> deleteAttachInfo(
            @RequestPart("fileUrl") String url) {
        File targetFile = new File("d:/files" + url);
        if (!targetFile.exists()) {
            return Result.fail("FILE_NOT_EXIST", "文件不存在");
        }
        boolean success = targetFile.delete();
        if (!success) {
            return Result.fail("FILE_DELETE_FAILED", "文件删除失败");
        }
        return Result.success();
    }
}
